﻿using Fleck;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Skybot.Net.WebSockets
{
    /// <summary>
    /// WebSocket实现
    /// </summary>
    public class SkybotWebSocket 
    {

        /// <summary>
        /// 新客户端接入
        /// </summary>
        public event System.Windows.RoutedPropertyChangedEventHandler<WebSocketConnection> OnAccpeted;

        /// <summary>
        /// 客户端关闭
        /// </summary>
        public event System.Windows.RoutedPropertyChangedEventHandler<WebSocketConnection> OnClosed;

        /// <summary>
        /// WebSocket服务
        /// </summary>
        WebSocketServer server;

        /// <summary>
        /// 需要创建一个监听的端口,一个实例只能调用一此此方法
        /// </summary>
        /// <param name="url"></param>
        public void Start(string url = "ws://0.0.0.0:8181")
        {
            if (server != null)
            {
                throw new NotSupportedException("一个实例不支持多次调用此方法.");
            }


            FleckLog.Level = LogLevel.Info;

            //初始化服务
            //使用此方法可以防止多次初始化
            System.Threading.LazyInitializer.EnsureInitialized<WebSocketServer>(ref server, () =>
            {
                server = new WebSocketServer(url);

                server.Start(socket =>
                {
                    socket.OnOpen = () =>
                    {
                        var conn = (WebSocketConnection)socket;
                        if (OnAccpeted != null)
                        {
                            OnAccpeted(this, new System.Windows.RoutedPropertyChangedEventArgs<WebSocketConnection>(null, conn));
                        }
                    };
                    socket.OnClose = () =>
                    {
                        var conn = (WebSocketConnection)socket;
                        if (OnClosed != null)
                        {
                            OnClosed(this, new System.Windows.RoutedPropertyChangedEventArgs<WebSocketConnection>(null, conn));
                        }
                    };

                });

                return server;
            });



        }


        protected void Send(IWebSocketConnection s, string message)
        {
            WebSocketConnection conn = s as WebSocketConnection;

            s.Send(string.Format("{0}:{1};Echo:  {2},{3}", conn.Socket.RemoteIpAddress, conn.Socket.RemotePort.ToString("D5"), message, DateTime.Now));
        }


    }
}
